package com.kmis.common.security;

import cn.hutool.json.JSONUtil;
import com.kmis.services.IUserService;
import com.kmis.utils.JwtUtil;
import com.kmis.vo.UserVo;
import com.kmis.web.ApiResult;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author moc
 * 自定义登录验证和登录返回数据
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

   private final IUserService userService;

    public LoginSuccessHandler(IUserService userService) {
        this.userService = userService;
    }


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream =
                response.getOutputStream();
        //获取用户名
        String username = authentication.getName();
        //使用用户名生成token
        UserVo currentUser = userService.getByUserName(username);
        String token = JwtUtil.genJwtToken(username);

        outputStream.write(JSONUtil.toJsonStr(ApiResult.ok("登录成功！").put("token",token).put("userInfo",currentUser)).getBytes());

        outputStream.flush();

        outputStream.close();
    }
}
